<template>
  <div>
    <el-dialog v-if="load" :title="title" v-model="visible" align-center width="640px" @close="handleClose" :close-on-click-modal="false">
      <el-form :model="formData" :rules="rules" ref="ruleFormRef" class="formw200" label-width="160px">
        <el-form-item label="规则名称" prop="rule_name">
          <el-input class="input" v-model="formData.rule_name" placeholder="规则名称" />
        </el-form-item>
        <el-form-item label="规则类型" prop="rule_type">
          <el-select v-model="formData.rule_type" class="input" collapse-tags clearable placeholder="规则类型" @change="ruleTypeChange">
            <el-option v-for="(d, i) in ruleTypeOption" :key="i" :label="d.label" :value="d.value"></el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="平台" prop="platform_id">
          <el-select v-model="formData.platform_id" class="input" collapse-tags placeholder="平台" @change="changePlatform">
            <el-option v-for="(d, i) in platformList" :key="i" :label="d.platform_name" :value="d.platform_id"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="站点" class="mr-[0]">
          <el-select v-model="formData.site" class="w_80" filterable multiple collapse-tags clearable placeholder="站点" @change="changeSite">
            <el-option v-for="(d, i) in siteList" :key="i" :label="d.site_abbrev" :value="d.site_id"></el-option>
          </el-select>
          <el-button type="primary" @click="checkAllSite">全选</el-button>
        </el-form-item>
        <el-form-item label="店铺" class="mr-[0]">
          <el-select v-model="formData.shop_id" class="w_80" filterable multiple collapse-tags clearable placeholder="店铺">
            <el-option v-for="(d, i) in shopList" :key="i" :label="d.shop_name" :value="d.shop_id"></el-option>
          </el-select>
          <el-button type="primary" @click="checkAllShop">全选</el-button>
        </el-form-item>

        <el-form-item label="币种类型" v-if="formData.rule_type == 2" prop="currency">
          <SelectCurrency class="input" v-model="formData.currency" filterable valueKey="label" placeholder="币种"> </SelectCurrency>
        </el-form-item>
        <el-form-item label="订单金额范围" required v-if="formData.rule_type == 2" style="margin-bottom: 0">
          <el-form-item prop="start_sell_price" class="mr-[4px]">
            <el-input class="w-[180px]" v-model="formData.start_sell_price" type="number" placeholder="请输入" />
          </el-form-item>
          <span class="text-gray-500 mx-[2px] mb-[18px]">-</span>
          <el-form-item prop="close_sell_price" class="ml-[4px]">
            <el-input class="w-[180px]" v-model="formData.close_sell_price" type="number" placeholder="请输入" />
          </el-form-item>
        </el-form-item>

        <el-form-item label="利润检测" class="h-[32px]">
          <el-radio-group v-model="formData.detection_type">
            <el-radio :value="1">利润率</el-radio>
            <el-radio :value="2">利润</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="订单利润率最低值" prop="order_minimum">
          <template #label>
            <div class="flex items-center">
              订单利润率最低值
              <el-tooltip class="box-item" effect="dark" content="订单利润率低于该值时，系统会提示并加入问题单，需业务人员确认是否发货" placement="top">
                <svg-icon icon-class="warning" />
              </el-tooltip>
            </div>
          </template>
          <el-input class="input" v-model="formData.order_minimum" type="number" placeholder="请输入">
            <template #append>{{ formData.detection_type == 1 ? "%" : "CNY" }}</template>
          </el-input>
        </el-form-item>
        <div v-if="formData.rule_type == 1">
          <el-form-item label="订单SKU" prop="sku">
            <!-- <template #label>
              <span style="position: relative">
                订单SKU
                <span style="position: absolute; left: 500px; width: 122px; text-align: right">
                  <el-button type="danger" link @click="clearSku"> 清空</el-button>
                  <el-button type="primary" size="small" @click="showSKU"> 添加</el-button>
                </span>
              </span>
            </template> -->
            <div class="skuBox">
              <p v-for="(item, index) in formData.sku" :key="index">
                {{ item }}
                <svg-icon icon-class="close_red" @click="delSku(index)" />
              </p>
            </div>
            <div class="ml-[280px]">
              <el-button type="danger" link @click="clearSku"> 清空</el-button>
              <el-button type="primary" size="small" @click="showSKU"> 添加</el-button>
            </div>
          </el-form-item>
        </div>

        <el-form-item label="状态" class="mr-[0]">
          <el-switch v-model="formData.status" :active-value="1" :inactive-value="0" inline-prompt active-text="启用" inactive-text="禁用"></el-switch>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="close">取 消</el-button>
        <el-button type="primary" :loading="loadings.submit" @click="submit">保 存</el-button>
      </template>
    </el-dialog>
    <SelectProduct v-model:visible="visibleProductSku" :multiple="true" :selectIds="formData.sku" @uploadSku="handleProductSku"> </SelectProduct>
  </div>
</template>

<script setup>
import { ref, onMounted, reactive, toRefs } from "vue"
import { profitSettingDetail, profitSettingCreate, profitSettingUpdate } from "../api"
import { ElMessage } from "element-plus"
import { getPlatformOptions, getSiteOptions, getShopOptions } from "@/api/public"
import SelectCurrency from "@/components/Selects/Currency"
import SelectProduct from "@/components/SelectProduct"

const ruleFormRef = ref()
const load = ref(false)
const visible = ref(false)
let loadings = reactive({})
// 声明接收参数
const props = defineProps({
  title: {
    type: String,
    default: "新增",
  },
  ruleTypeOption: {
    type: Object,
    default: [],
  },
})
const data = reactive({
  formData: {
    rule_type: "",
    platform_id: "",
  },
  isType: false,
  platformList: [],
  siteList: [],
  shopList: [],
})
const { formData, isType, platformList, siteList, shopList } = toRefs(data)
const { title, ruleTypeOption } = toRefs(props)
const emit = defineEmits(["close", "confirm"])
//清空sku
const clearSku = () => {
  formData.value.sku = ""
}
//订单金额范围
const priceRadius = (rule, value, callback) => {
  if (!value) {
    return callback(new Error("不能为空"))
  } else {
    if (Number(value) > Number(formData.value.start_sell_price)) {
      callback()
    } else {
      return callback(new Error("请输入正确的金额"))
    }
  }
}
const rules = reactive({
  rule_name: [{ required: true, message: "名称不能为空", trigger: "blur" }],
  rule_type: [{ required: true, message: "请选择", trigger: "change" }],
  platform_id: [{ required: true, message: "请选择", trigger: "change" }],
  order_minimum: [{ required: true, message: "不能为空", trigger: "blur" }],
  sku: [{ required: true, message: "不能为空", trigger: "change" }],
  order_minimum: [{ required: true, message: "不能为空", trigger: "blur" }],
  currency: [{ required: true, message: "不能为空", trigger: "change" }],
  close_sell_price: [{ required: true, validator: priceRadius, trigger: "blur" }],
  start_sell_price: [{ required: true, message: "不能为空", trigger: "blur" }],
})
const ruleTypeChange = (e) => {
  if (e == 1) {
    formData.value.sku = []
  }
}
// 打开弹窗
const open = (row = {}) => {
  if (!load.value) {
    load.value = true
  }
  if (row.id) {
    isType.value = true
    profitSettingDetail({ id: row.id }).then((res) => {
      loadings = reactive({})
      visible.value = true
      getSite(res.data.platform_id)
      getShop(res.data.platform_id, res.data.site)
      formData.value = res.data
    })
  } else {
    loadings = reactive({})
    isType.value = false
    visible.value = true
  }
}
// 关闭弹窗
const close = () => {
  formData.value = {}
  ruleFormRef.value.resetFields()
  visible.value = false
}

const handleClose = () => {
  close()
  emit("close")
}
// 提交
const submit = () => {
  let { validate } = ruleFormRef.value
  validate((valid) => {
    if (valid) {
      loadings.submit = true
      if (isType.value) {
        profitSettingUpdate(formData.value)
          .then((res) => {
            ElMessage({ message: "保存成功！", type: "success" })
            emit("confirm")
            close()
          })
          .finally(() => {
            loadings.submit = false
          })
      } else {
        profitSettingCreate(formData.value)
          .then((res) => {
            ElMessage({ message: "保存成功！", type: "success" })
            emit("confirm")
            close()
          })
          .finally(() => {
            loadings.submit = false
          })
      }
    }
  })
}

// 获取平台
const getPlatform = async () => {
  try {
    const res = await getPlatformOptions()
    platformList.value = res.data
  } catch (e) {
    throw Error(e)
  }
}

// 选择平台
const changePlatform = async (val) => {
  siteList.value = []
  shopList.value = []
  formData.value.site = ""
  formData.value.shop_id = ""
  getSite(val)
}

// 获取站点
const getSite = async (id) => {
  try {
    const res = await getSiteOptions({
      platform_ids: [id],
    })
    siteList.value = res.data
  } catch (e) {
    throw Error(e)
  }
}

// 选择站点
const changeSite = async (val) => {
  shopList.value = []
  formData.value.shop_id = ""
  getShop(formData.value.platform_id, val)
}

// 获取店铺列表
const getShop = async (platform_id, site_ids) => {
  try {
    const res = await getShopOptions({
      site_ids,
      platform_ids: [platform_id],
    })
    shopList.value = res.data
  } catch (e) {
    throw Error(e)
  }
}

// 全选站点
const checkAllSite = async () => {
  if (siteList.value.length == 0) {
    ElMessage.error("站点列表为空")
    return
  }
  const site_ids = siteList.value.map((i) => i.site_id)
  formData.value.site = site_ids
  getShop(formData.value.platform_id, site_ids)
}

// 全选店铺
const checkAllShop = async () => {
  if (shopList.value.length == 0) {
    ElMessage.error("店铺列表为空")
    return
  }
  const shop_ids = shopList.value.map((i) => i.shop_id)
  formData.value.shop_id = shop_ids
}

const visibleProductSku = ref(false)

const showSKU = async () => {
  visibleProductSku.value = true
}

const handleProductSku = async (list) => {
  formData.value.sku = list.map((i) => i.sku)
}

//删除sku
const delSku = (index) => {
  formData.value.sku.splice(index, 1)
}

onMounted(() => {
  getPlatform()
})

defineExpose({ open })
</script>
<style lang="scss" scoped>
.formw200 {
  .el-form-item {
    margin-right: 12px;
    // width: 300px;
  }
  :deep(.input) {
    // width: 200px;
    width: 380px;
  }
  .w_80 {
    width: 320px;
  }
  // .w-562 {
  //   width: 562px;
  // }
}
.skuBox {
  width: 380px;
  min-height: 100px;
  border: 1px solid #c0c4cc;
  border-radius: 5px;
  margin-top: 10px;
  padding: 5px 10px;
  max-height: 300px;
  overflow: auto;
  cursor: pointer;
  p {
    display: flex;
    justify-content: space-between;
    align-items: center;
  }
}
</style>
